// src/store/tab.ts
import { defineStore } from 'pinia';

export interface TabItem {
  title: string;
  path: string;
  name: string;
  keepAlive?: boolean;
}

export const STORAGE_KEY = 'APP_TABS';

export const useTabStore = defineStore('tab', {
  state: () => ({
    tabs: [] as TabItem[],
    activePath: '',
  }),

  getters: {
    keepAliveNames: (state) => state.tabs.filter((t) => t.keepAlive).map((t) => t.name),
  },

  actions: {
    /** 加载本地 tabs */
    loadTabs() {
      const data = localStorage.getItem(STORAGE_KEY);
      if (data) {
        const parsed = JSON.parse(data);
        this.tabs = parsed.tabs || [];
        this.activePath = parsed.activePath || '';
      }
    },

    /** 持久化保存 */
    saveTabs() {
      localStorage.setItem(
        STORAGE_KEY,
        JSON.stringify({
          tabs: this.tabs,
          activePath: this.activePath,
        }),
      );
    },

    addTab(tab: TabItem) {
      if (!this.tabs.find((t) => t.path === tab.path)) {
        this.tabs.push(tab);
      }
      this.activePath = tab.path;
      this.saveTabs();
    },

    removeTab(path: string) {
      const idx = this.tabs.findIndex((t) => t.path === path);
      if (idx !== -1) {
        this.tabs.splice(idx, 1);
      }

      // 若删除的是当前页，也要更新 activePath
      if (this.activePath === path) {
        const last = this.tabs[this.tabs.length - 1];
        this.activePath = last ? last.path : '';
      }

      this.saveTabs();
    },

    setActive(path: string) {
      this.activePath = path;
      this.saveTabs();
    },
  },
});
